package com.fengba.nanzhi.tabbar04.wz;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.Preferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.support.v4.app.ActivityCompat.startActivityForResult;

public class IdnumberActivity extends AppCompatActivity {

    private ImageView imageViewzm,imageViewfm,imageViewzmimg,imageViewfmimg;
    private TextView djsm1,djsm2,xiugai1,xiugai2,xiugai3;
    private EditText IdnumberName,IdnumberId,IdnumberTime;
    private Button mBtnxyb;
    private String user_id;
    private ImageButton smsfzfh;

    private static final int REQUEST_CODE_PICK_IMAGE_FRONT = 201;
    private static final int REQUEST_CODE_PICK_IMAGE_BACK = 202;
    private static final int REQUEST_CODE_CAMERA = 102;
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private int i,x=0,y=0;
    private String url;
    int zanshi = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Token();
        setContentView(R.layout.wz_activity_idnumber);
        imageViewzm = findViewById(R.id.idnumberzm);
        imageViewfm = findViewById(R.id.idnumberfm);
        imageViewzmimg = findViewById(R.id.idnumberzmimg);
        imageViewfmimg = findViewById(R.id.idnumberfmimg);
        djsm1 = findViewById(R.id.djsm1);
        djsm2 = findViewById(R.id.djsm2);
        IdnumberName = findViewById(R.id.Idnumber_name);
        IdnumberId = findViewById(R.id.Idnumber_id);
        IdnumberTime = findViewById(R.id.Idnumber_Time);
        xiugai1 = findViewById(R.id.sfzxiugai1);
        xiugai2 = findViewById(R.id.sfzxiugai2);
        xiugai3 = findViewById(R.id.sfzxiugai3);
        mBtnxyb = findViewById(R.id.sfzBtn);
        //返回
        smsfzfh = findViewById(R.id.smsfzfh);
        smsfzfh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        imageViewzmimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                x=0;
                Intent intent = new Intent(IdnumberActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
                imageViewzmimg.setImageDrawable(null);
                imageViewzm.setVisibility(imageViewzm.VISIBLE);
                djsm1.setVisibility(djsm1.VISIBLE);

            }
        });

        // 身份证反面拍照
        imageViewfmimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                y=0;
                Intent intent = new Intent(IdnumberActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
                imageViewfmimg.setImageDrawable(null);
                imageViewfm.setVisibility(imageViewfm.VISIBLE);
                djsm2.setVisibility(djsm2.VISIBLE);
            }
        });

        xiugai1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(xiugai1.getText().equals("修改")) {
                    showSoftInputFromWindow(IdnumberActivity.this,IdnumberName);
                    IdnumberId.setFocusable(false);
                    IdnumberTime.setFocusable(false);
                    xiugai1.setText("确定");
                    xiugai2.setText("修改");
                    xiugai3.setText("修改");
                }else{
                    InputMethodManager imm = (InputMethodManager) IdnumberActivity.this
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(IdnumberName.getWindowToken(), 0);
                    IdnumberName.setFocusable(false);
                    xiugai1.setText("修改");
                }
            }
        });
        xiugai2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(xiugai2.getText().equals("修改")) {
                    showSoftInputFromWindow(IdnumberActivity.this,IdnumberId);
                    IdnumberTime.setFocusable(false);
                    IdnumberName.setFocusable(false);
                    xiugai1.setText("修改");
                    xiugai2.setText("确定");
                    xiugai3.setText("修改");
                }else{
                    InputMethodManager imm = (InputMethodManager) IdnumberActivity.this
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(IdnumberId.getWindowToken(), 0);
                    IdnumberId.setFocusable(false);
                    xiugai2.setText("修改");
                }
            }
        });
        xiugai3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(xiugai3.getText().equals("修改")) {
                    showSoftInputFromWindow(IdnumberActivity.this,IdnumberTime);
                    IdnumberId.setFocusable(false);
                    IdnumberName.setFocusable(false);
                    xiugai1.setText("修改");
                    xiugai2.setText("修改");
                    xiugai3.setText("确定");
                }else{
                    InputMethodManager imm = (InputMethodManager) IdnumberActivity.this
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(IdnumberTime.getWindowToken(), 0);
                    IdnumberTime.setFocusable(false);
                    xiugai3.setText("修改");
                }
            }
        });

        mBtnxyb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(x==0||y==0||IdnumberName.getText().toString().trim().equals("")||IdnumberId.getText().toString().trim().equals("")||IdnumberTime.getText().toString().trim().equals("")){
                    showToast(IdnumberActivity.this,"请完善信息");
                }else {
                    Object user_info = Preferences.getParam(IdnumberActivity.this, "user_info", "");
                    try {
                        JSONObject myJson = new JSONObject(user_info.toString());

                        //账号
                        user_id = myJson.get("id").toString();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Bitmap image1 = ((BitmapDrawable) imageViewzmimg.getDrawable()).getBitmap();
                    Bitmap image2 = ((BitmapDrawable) imageViewzmimg.getDrawable()).getBitmap();


                    sendImage(image1, image2);
                    Intent intent = new Intent(IdnumberActivity.this, SMCardActivity.class);
                    intent.putExtra("Idnumber_name", IdnumberName.getText().toString());
                    intent.putExtra("Idnumber_id", IdnumberId.getText().toString());
                    startActivity(intent);
                }
            }
        });
    }

    public void Token(){
        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                // 调用成功，返回AccessToken对象
                showToast(IdnumberActivity.this,result.toString());
                String token = result.getAccessToken();
            }
            @Override
            public void onError(OCRError error) {
                // 调用失败，返回OCRError子类SDKError对象
                showToast(IdnumberActivity.this,error.toString());
            }
        }, getApplicationContext(), "7outqMHRUg9Fjsd3RFs0PZNG", "AIbOlma4wGOchToB6bfUs3Ac41GpB6Wh");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                // 获取调用参数
                String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
                // 通过临时文件获取拍摄的图片
                String filePath = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
                url = filePath;
                if (!TextUtils.isEmpty(contentType)) {
                    if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
                        i = 1;
                    } else if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                        i = 2;
                        recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
                    }
                }
            }
        }
    }

    private void recIDCard(String idCardSide, String filePath) {
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));
        // 设置身份证正反面
        param.setIdCardSide(idCardSide);
        // 设置方向检测
        param.setDetectDirection(true);
        // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setImageQuality(20);
        //final Uri uri1 = Uri.fromFile(new File(url));
        OCR.getInstance().recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                if (result != null) {
                    if(i==1){
                    //showToast(IdnumberActivity.this, result.toString());
                        InputMethodManager imm = (InputMethodManager) IdnumberActivity.this
                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(IdnumberName.getWindowToken(), 0);
                        imageViewzmimg.setImageURI(Uri.parse(url));
                        imageViewzm.setVisibility(imageViewzm.GONE);
                        djsm1.setVisibility(djsm1.GONE);
                        IdnumberName.setText(result.getName().toString());
                        IdnumberId.setText(result.getIdNumber().toString());
                       // IdnumberName.setText();
                        x=1;
                    }else{
                        InputMethodManager imm = (InputMethodManager) IdnumberActivity.this
                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(IdnumberName.getWindowToken(), 0);
                        imageViewfmimg.setImageURI(Uri.parse(url));
                        imageViewfm.setVisibility(imageViewfm.GONE);
                        djsm2.setVisibility(djsm2.GONE);
                        IdnumberTime.setText(result.getSignDate().toString()+"-"+result.getExpiryDate());
                        y=1;
                    }
                }

            }

            @Override
            public void onError(OCRError error) {
                showToast(IdnumberActivity.this, error.getMessage());
            }
        });
    }

    public static void showToast(final Activity ctx, final String msg) {
        // 判断是在子线程，还是主线程
        if ("main".equals(Thread.currentThread().getName())) {
            Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
        } else {
            // 子线程
            ctx.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }



    /**
     * EditText获取焦点并显示软键盘
     */
    public void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        InputMethodManager imm = (InputMethodManager) getSystemService(activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 上传身份证图片
     */
    public void IdnumberImage(){
        Object user_info = Preferences.getParam(IdnumberActivity.this,"user_info","");
        try {
            JSONObject myJson = new JSONObject(user_info.toString());

            //账号
            user_id = myJson.get("id").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Bitmap image1 = ((BitmapDrawable)imageViewzmimg.getDrawable()).getBitmap();
        Bitmap image2 = ((BitmapDrawable)imageViewzmimg.getDrawable()).getBitmap();
        String img1 =  zhuan(image1);
        String img2 =  zhuan(image2);
        OKManager.getInstance().type1025(user_id, img1, img2, new OKManager.func4() {
            @Override
            public void onResponse(JSONObject jsonObject) {

                Intent intent = new Intent(IdnumberActivity.this,SMCardActivity.class);
                intent.putExtra("Idnumber_name",IdnumberName.getText().toString());
                intent.putExtra("Idnumber_id",IdnumberId.getText().toString());
                startActivity(intent);
            }

            @Override
            public void onFailure(String string) {
                showToast(IdnumberActivity.this,"网络错误");
            }
        });
    }
    public String zhuan(Bitmap bitmap){
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        //第二步:利用Base64将字节数组输出流中的数据转换成字符串String
         byte[] byteArray = byteArrayOutputStream.toByteArray();
        String imageString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
        return imageString;
    }

//    public static String convertIconToString(Bitmap bitmap)
//    {
//
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
//        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//        byte[] appicon = baos.toByteArray();// 转为byte数组
//        return Base64.encodeToString(appicon, Base64.DEFAULT);
//    }
    /**
     * 上传图片到服务器
     *
     * @param bitmap1
     */
    private void sendImage(Bitmap bitmap1,Bitmap bitmap2) {

        File file1 = new File(Environment.getExternalStorageDirectory() + "/idnumber_zm");
        File file2 = new File(Environment.getExternalStorageDirectory() + "/idnumber_fm");
        if (!file1.exists())
            file1.mkdirs();
        if (!file2.exists())
            file2.mkdirs();
        File imgFile1 = new File(file1.getAbsolutePath() + "/idnumber_zm1.jpeg");
        File imgFile2 = new File(file2.getAbsolutePath() + "/idnumber_fm1.jpeg");
        if (imgFile1.exists())
            imgFile1.delete();
        if (imgFile2.exists())
            imgFile2.delete();
        try {
           /* FileOutputStream outputStream1 = new FileOutputStream(imgFile1);
            FileOutputStream outputStream2 = new FileOutputStream(imgFile2);
            bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, outputStream1);
            bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, outputStream2);
            outputStream1.flush();
            outputStream1.close();
            outputStream2.flush();
            outputStream2.close();*/
            FileOutputStream bos1 = new FileOutputStream(imgFile1);
            FileOutputStream bos2 = new FileOutputStream(imgFile2);
            bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, bos1);
            bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, bos2);
            bos1.flush();
            bos1.close();

            bos2.flush();
            bos2.close();

            OKManager.getInstance().type1027(user_id, imgFile1,imgFile2);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
